<?php namespace App\Http\Controllers\Admin;

use App\Http\Requests;
use App\Http\Controllers\Controller;

use App\Job;
use Illuminate\Http\Request;

class JobController extends Controller
{
//显示内容
    public function getIndex(Request $request)
    {
        $own_name = trim($request->get('own_name', ''));
        $appends = [];

        $handler = Job::orderBy('created_at', 'DESC');

        if ($own_name) {
            $handler->where('own_name', 'like', '%' . $own_name . '%');
            $appends['own_name'] = $own_name;
        }

        $px = $request->get('px');
        $tuijian = $request->get('tuijian');
        $list = $handler->paginate(config('site.admin.pageSize'));


        return view('admin.job.index', [
            'list' => $list,
            'own_name' => $own_name,
            'tuijian' => $tuijian,
            'appends' => $appends,
            'px' => $px,
        ]);
    }

    public function getUpdate($id = 0)
    {
        $model = Job::findOrNew($id);
        return view('admin.job.update', ['model' => $model]);
    }


//提交获取的数据
    public function postUpdate(Request $request, $id = 0)
    {
        $model = Job::findOrNew($id);
        $data = $request->all();

        if (!$model->id) {
            $model->user_id = \Auth::user()->id;
        }

        $attributes = [
            'own_name' => '雇主姓名',
            'content' => '案例内容',
        ];
        $rules = [
            'own_name' => 'required',
            'content' => 'required',
        ];
        $address['s_province'] = $data['s_province'];
        $address['s_city'] = $data['s_city'];
        $address['s_county'] = $data['s_county'];
        $address['detial'] = $data['address'];
        $data['address'] = json_encode($address);
        unset($data['s_province']);
        unset($data['s_city']);
        unset($data['s_county']);
        $validator = \Validator::make($data, $rules, ['required' => ':attribute不能为空'], $attributes);
        if ($validator->fails()) {
            $message = $validator->messages();
            $ret['message'] = '保存出错';
            $ret['state'] = 'error';
            foreach ($attributes as $k => $attr) {
                if ($message->has($k)) {
                    $ret['message'] = $message->first($k);
                    break;
                }
            }
        } else {
            $model->fill($data);
            $model->save();//写入数据库

            if ($model->id) {
                $ret = ['state' => 'success', 'message' => '操作成功'];
            } else
                $ret['message'] = '保存出错';
        }

        return \Response::json($ret);
    }

    public function postDelete($id)
    {
        $ret = ['state' => 'fail', 'message' => '未知错误，请刷新重试'];
        if (Job::destroy($id))
            $ret = ['state' => 'success', 'message' => '删除成功'];

        return \Response::json($ret);
    }
}
